<?php

/**
 * 这是一个关于PHP异常处理的示例
 * User: ford
 * Date: 15-6-19
 * Time: 上午8:49
 */

/**
 * 自定义一个异常处理类
 * Class NoNumericException
 */
class NoNumericException extends Exception {
	private $value;

	function __construct($value) {
		$this->value = $value;
	}

	public function info() {
		echo "Error: The value $this->value is not numeric.\n";
	}
}

//下面是异常抛出演示代码
//注意：$argv[]是包含命令行参数的全局数组变量，这个要在命令行下执行；还有一个表示参数个数的全局变量$argc
try {
	$a = "my string";

	if(!is_numeric($argv[1])) {
		throw new NoNumericException($argv[1]);
	}
	if(!is_numeric($argv[2])) {
		throw new NoNumericException($argv[2]);
	}
	if($argv[2] == 0) {
		throw new Exception("Illegal division by zero.\n");
	}

	echo 'Result: ' . $argv[1]/$argv[2] ."\n";
}
catch (NoNumericException $exc) {
	$exc->info();
	exit(-1);
}
catch(Exception $exc) {
	echo "Exception:";
	$code = $exc->getCode();
	if(!empty($code)) {
		echo "Error code:" . $code . "\n";
	}

	echo $exc->getMessage();
	exit(-1);
}

echo "Variable a=" . $a ."\n";